export function getElement(key) {
  return document.querySelector(`[data-key='${key}']`);
}

export function findClosetElement(container, point, query) {
  const elements = container.querySelectorAll(query);
  let result;
  let minDistance;
  elements.forEach(element => {
    const rect = element.getBoundingClientRect();
    if (rectContainsPoint(rect, point)) {
      result = element;
      return false;
    }
    const distance = rectPointMinDistance(rect, point);
    if (minDistance === undefined || minDistance > distance) {
      minDistance = distance;
      result = element;
    }
  });
  return result;
}

function rectPointMinDistance(rect, point) {
  let minDistance;
  const points = [
    [rect.left, rect.top],
    [rect.left, rect.bottom],
    [rect.right, rect.top],
    [rect.right, rect.bottom]
  ];
  points.forEach(item => {
    const dx = item[0] - point.x;
    const dy = item[1] - point.y;
    const distance = Math.sqrt(dx * dx + dy * dy);
    if (minDistance === undefined || minDistance > distance) {
      minDistance = distance;
    }
  });
  return minDistance;
}

function rectContainsPoint(rect, point) {
  const x = point.x > rect.x && point.x < rect.x + rect.width;
  const y = point.y > rect.y && point.y < rect.y + rect.height;
  return x && y;
}
